package com.tql;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class TestTx {
    public static void main(String[] args) {
        Jedis jedis=new Jedis("127.0.0.1",6379);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("hello","word");
        jsonObject.put("name","hh");
        //开启事务
        Transaction multi=jedis.multi();
        String result=jsonObject.toJSONString();
        try {
            multi.set("user1",result);
            multi.set("user2",result);
            multi.set("key1","2");
            //int 自增1
            multi.incr("key1");
            //自增定义常量
            multi.incrBy("key1",10);
            multi.exec();//执行事务
        }catch (Exception e){
            //如果执行异常，放弃事务
            multi.discard();
            e.printStackTrace();;
        }finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            System.out.println(jedis.get("key1"));
            jedis.close();
        }
    }
}
